<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Login extends My_Controller{

    public function __construct()
    {
        parent::__construct();
        $this->load->model("User_model","user");
    }

    /**
     *------------------------------------------------------------------------------------------------------------------
     * @title：用户登录接口
     * @action：/login/do_login
     * @method：GET
     * @param：loginName，类型：STRING，必须：YES
     * @param：password，类型：STRING，必须：YES
     * @author:：柏凯
     *------------------------------------------------------------------------------------------------------------------
     */
    public function do_login()
    {
        file_put_contents("mylog.txt", file_get_contents('php://input')."\r\n",FILE_APPEND);
        
        $params['loginName']=trim($this->queryData["loginName"]);
        $params['password']=trim($this->queryData["password"]);
      
        $validate = new Validate([
            'loginName' => 'require|string',
            'password'=>'require|string',
        ]);
        if (!$validate->check($params)) {
            $this->errorCode = 50003;
            $this->errorMessage = $validate->getError();
            $this->createApi();
            exit;
        }
        $result=$this->user->login($params['loginName'],$params['password']);
        if(in_array($result, ['50012','50013'])){
                $this->errorCode = $result;
                $this->createApi();exit;
            }
        if(empty($result))
        {
             $this->errorCode = 50011;
            $this->errorMessage = $validate->getError();
            $this->createApi();
            exit;
        }
        $this->createApi($result);
        exit;
        
    }

    public function logout()
    {
        $token=trim($this->queryData["token"]);
        if(!$token){
            $this->errorCode = 50003;
            $this->createApi();exit();
        }
        $userInfo = $this->user->getUserInfoByToken($token);
        if(empty($userInfo)){
            $this->errorCode = 50006;
            $this->createApi(); exit();
        }
        $AccountID = $userInfo['AccountID'];
        $res = $this->user->logout($AccountID);
        $this->createApi();
    }

    //第三方校验登陆
    public function snsLogin()
    {
        $params['openid'] = $this->queryData['openid'];
        $params['unionid'] = $this->queryData['unionid'];
        $params['type'] = 'wechat'; // 微信登录
        $validate = new Validate([
            'openid' => 'require|string',
            'unionid'=>'require|string',
            'type'=>'require|string',
        ]);
        if (!$validate->check($params)) {
            $this->errorCode = 50003;
            $this->errorMessage = $validate->getError();
            $this->createApi();
            exit;
        }
        $result = ['isbind'=>false,'userInfo'=>new stdClass()];
        $loginData = $this->user->sns_login($params);
		if(in_array($loginData, ['50012','50013'])){
                $this->errorCode = $loginData;
                $this->createApi();exit;
            }
        if($loginData)
        {
            $result = ['isbind'=>true,'userInfo'=>$loginData];
        }
        $this->createApi($result);exit;
    }
    //第三方绑定手机号发送验证码
    public function snsSendSms(){
        // file_put_contents("mylog.txt", file_get_contents('php://input')."注册\r\n",FILE_APPEND);
        $params['reginMobile'] = $this->queryData['reginMobile'];
        $params['openid'] = $this->queryData['openid'];
        $params['unionid'] = $this->queryData['unionid'];
        $params['type'] = $this->queryData['type'];
        $validate = new Validate([
            'reginMobile' => 'require|string',
            'type' => 'require|string',
            'openid' => 'require|string',
        ]);
        if (!$validate->check($params)) {
            $this->errorCode = 50003;
            $this->errorMessage = $validate->getError();
            $this->createApi();
            exit;
        }

        //判断当天本用户登录次数 不能超过三次
        /*$maxSendCnt = $this->config->item('maxSendCnt');
        if($this->user->checkSendCnt($reginMobile, $maxSendCnt) == false){
            $this->errorCode = API_ERROR_SMS_OVER;
            $this->createApi();exit();
        }*/
        $result['isRegistMobile'] = false;
        //判断用户是否存在
        $bindStatus = $this->user->check_bind_status($params);
        if($bindStatus['isbind'] == true){
            $this->errorCode = 60007;
            $this->createApi();exit;
        };
        if($bindStatus['isRegistMobile']){
            $result['isRegistMobile'] = true;
        };
        require_once(APPPATH.'third_party/yuntongxun/SendTemplateSMS.php');
        $mcode = strtolower(random_string('numeric',6));
        //验证码生成,并执行发送短信，60秒有效期
        $datas = array($mcode,10);
        $res = sendTemplateSMS($params['reginMobile'],$datas,133051);
        $data = array("mcode"=>$mcode,"expiretime"=>time()+600);
        $this->user->saveSmsStatus($params['reginMobile'],$data,$maxSendCnt);
        if(empty($res)){
            $this->errorCode = 60007;
            $this->createApi();exit;
        }
        $this->createApi($result);
    }

    //第三方绑定手机号
    public function snsBindPhone()
    {
        $params['username'] = $this->queryData['mobile'];
        $params['password'] = $this->queryData['password'];
        $params['mcode'] = $this->queryData['mcode'];
        $params['type'] = $this->queryData['type'];
        $params['openid'] = $this->queryData['openid'];
        $params['nickname'] = $this->queryData['nickname'];
        $params['headimgurl'] = $this->queryData['headimgurl'];
        $params['unionid'] = $this->queryData['unionid'];
        $params['isRegistMobile'] = $this->queryData['isRegistMobile'];
        $validate = new Validate([
            'username' => 'require|string',
            'mcode' => 'require|string',
            'type' => 'require|string',
            'openid' => 'require|string',
            'nickname' => 'require|string',
            'headimgurl' => 'require|string',
            'isRegistMobile' => 'require|number',
        ]);
        if (!$validate->check($params)) {
            $this->errorCode = 50003;
            $this->errorMessage = $validate->getError();
            $this->createApi();
            exit;
        }
        // if($params['isRegistMobile'] == false)
        $mcodeInfo = $this->user->get_mcodeInfo($params['username']);
        //判断验证码是否正确
        if($params['mcode'] != $mcodeInfo['mcode']){
            $this->errorCode = 60004;
            $this->createApi();exit();
        }
        //判断是否过期
        if($mcodeInfo['expiretime'] < time()) {
            $this->errorCode = 60002;
            $this->createApi();exit;
        }
        $params['reginMobile'] = $params['username'];
        $bindStatus = $this->user->check_bind_status($params);
        if($bindStatus['isbind']){
            $this->errorCode = 60007;
            $this->createApi();exit;
        }
        if($params['isRegistMobile'] == true)
        {
            //执行绑定
            $userInfo = $this->user->get_userinfo('', $params['username']);
            if(empty($userInfo))
            {
                $this->errorCode = 60009;
                $this->createApi();exit();
            }
            $params['AccountID'] = $userInfo['AccountID'];
            $res = $this->user->bingPhone($params);
            
        }else{
            //执行注册并绑定 显示密码
            $res = $this->user->add_thirdUser($params);
            $points = $this->setPoint(1);
            $data = array(
                'AccountID'=>$res['AccountID'],
                'createtime'=>date('Y-m-d',time()),
                'points'=>$points,
                'type'=>1
                );
            $this->load->model("Point_model","point");
            $this->point->addPoints($res['AccountID'],$data);
        }
        $this->createApi($res);
    }
	
	public function checkLoginStatus()
	{
		$token      = isset($this->queryData['token']) ? $this->queryData['token'] : '';
		$this->checkLogin($token);
		$this->createApi();exit;
	}
        
}

/* End of file login.php */
/* Location: ./application/controllers/login.php */
